package com.appstore.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.appstore.common.AjaxResult;
import com.appstore.common.AliOSSUtils;
import com.appstore.common.constant.FileType;
import com.appstore.common.utils.SecurityUtils;
import com.appstore.common.utils.spring.SpringUtils;
import com.appstore.domain.dto.AppModuleJson;
import com.appstore.domain.entity.App;
import com.appstore.service.AppImageService;
import com.appstore.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/app")
@Slf4j
public class AppController {

    //https://myohap.oss-cn-beijing.aliyuncs.com/software/

    //private static final String BASE_FILE_PATH = "src/main/resources/static/software/";
    //private static final String BASE_FILE_PATH = "D:\\chen_sdu\\workspace\\study-documents\\appstore (2)\\appstore\\RuoYi-Vue\\appstore-demo\\src\\main\\resources\\static\\software\\";
    private static final String BASE_FILE_PATH = "software/";

    private static final String BASE_UPLOAD_PATH = "D:\\chen_sdu\\workspace\\study-documents\\appstore (2)\\appstore\\RuoYi-Vue\\appstore-demo\\src\\main\\resources\\static\\software\\";
    private static final String BASE_AVATAR_UPLOAD_PATH = "D:\\chen_sdu\\workspace\\study-documents\\appstore (2)\\appstore\\RuoYi-Vue\\appstore-demo\\src\\main\\resources\\static\\avatar\\";
    private static final String BASE_DETAILS_IMAGES_UPLOAD_PATH = "D:\\chen_sdu\\workspace\\study-documents\\appstore (2)\\appstore\\RuoYi-Vue\\appstore-demo\\src\\main\\resources\\static\\images\\";
    @Resource
    private AppService appService;
    @Resource
    private AppImageService appImageService;

    //按rating排序
    @GetMapping
    public AjaxResult getAppList() {
        return AjaxResult.success(appService.getAppList());
    }

    /**
     * 根据app的属性查询，查询条件包括name，categoryId,description
     * @param app
     * @return
     */
    @PostMapping("/getByConditions")
    public AjaxResult getAppByConditions(@RequestBody App app) {
        return AjaxResult.success(appService.getAppByConditions(app));
    }

    /**
     * 根据应用id查询应用详情，包括评论图片等
     * @param id
     * @return
     */
    @GetMapping("/get_app_detail/{id}")
    public AjaxResult getAppDetail(@PathVariable Long id) {
        if(ObjectUtils.isEmpty(id)) return AjaxResult.error("请求参数为空");
        return AjaxResult.success(appService.getAppDetail(id));
    }


    /**
     * 获取新机必备
     * @return
     */
    @GetMapping("/get_essential_for_new_devices")
    public AjaxResult getEssentialForNewDevices(){
        return AjaxResult.success(appService.getEssentialForNewDevices());
    }

    /**
     * 新增
     * @param app
     * @return
     */
    @PostMapping
    public AjaxResult addApp(@RequestBody App app) {
        if(ObjectUtils.isEmpty(app)) return AjaxResult.error("请求参数为空");
        return AjaxResult.success(appService.addApp(app));
    }



    /**
     * 应用下载
     * @param appId
     * @param response
     */
    @GetMapping("/download/{appId}")
    public void download(@PathVariable Long appId, HttpServletResponse response) throws Exception {

        App app = appService.getAppById(appId);
        if(ObjectUtils.isEmpty(app)) return ;
        String downloadUrl = app.getDownloadUrl();
        if(ObjectUtils.isEmpty(downloadUrl)) return ;
        // 构造文件路径
        String filePath = BASE_FILE_PATH + downloadUrl;
        // 调用 AliOSSUtils 的下载方法
        AliOSSUtils aliOSSUtils = new AliOSSUtils();
        aliOSSUtils.downLoad(filePath, response);
        /*File file = new File(filePath);

        if (!file.exists()) {
            // 如果文件不存在，返回 404 错误
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            System.out.println("404");
            return;
        }

        // 设置 HTTP 响应头
        response.setContentType("application/vnd.android.package-archive");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setContentLengthLong(file.length());

        // 将文件写入响应流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }*/
    }


    /**
     * 上传文件功能
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/upload")
    public AjaxResult upload(
            @RequestParam("file") MultipartFile file,
            @RequestPart("app") String appString,
            @RequestParam("avatar") MultipartFile avatar,
            @RequestParam("detailImages") MultipartFile[] detailImages,
            @RequestParam("moduleJson") MultipartFile moduleJson) throws IOException {


        log.info("正在进入上传方法...");
        if(ObjectUtils.isEmpty(file)) return AjaxResult.error("上传文件为空");
        if(ObjectUtils.isEmpty(appString)) return AjaxResult.error("上传参数为空");

        //解析moduleJson
        // 读取 model.json 的内容
        String modelJsonContent = new String(moduleJson.getBytes(), StandardCharsets.UTF_8);
        log.error("modelJsonContent is " + modelJsonContent);
        AppModuleJson appModuleJson = AppJsonExtract(modelJsonContent);

        //App的JSON解析
        ObjectMapper objectMapper = new ObjectMapper();
        App app;
        try {
            app = objectMapper.readValue(appString,App.class);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("JSON解析失败" + e.getMessage());
        }
        app.setBundleName(appModuleJson.getBundleName());
        app.setVersion(appModuleJson.getVersionName());
        log.info("当前用户id为：" + SecurityUtils.getUserId());
        app.setDeveloperId(SecurityUtils.getUserId());
        //判断文件的bundleName是否重复
        String bundleName = app.getBundleName();
        App getByBundleName= appService.getAppByBundleName(bundleName);
        if(!ObjectUtils.isEmpty(getByBundleName)) return AjaxResult.error("文件上传失败，bundleName重复");

        try {
            AliOSSUtils aliOSSUtils = new AliOSSUtils();
            //app上传
            String fileUrl = aliOSSUtils.upload(file, FileType.software.getCode());
            //app avatar上传
            String avatarUrl = aliOSSUtils.upload(avatar, FileType.avatar.getCode());

            //插入app的详细数据
            String[] split = fileUrl.split("/");
            app.setIconUrl(avatarUrl);
            app.setDownloadUrl(split[split.length - 1].trim());
            int insert = appService.addApp(app);
            if(insert <=0 ) return AjaxResult.error();

            Long id = app.getId();
            //app detail_images上传
            for (MultipartFile detailImage : detailImages) {
                String imageUrl = aliOSSUtils.upload(detailImage, FileType.images.getCode());
                appImageService.addImage(id,imageUrl);
            }
            return AjaxResult.success("文件上传成功");

        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.error("文件上传失败" + e.getMessage());
        }
    }



    /**
     * 更新app功能
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/update")
    public AjaxResult update(
            @RequestParam(value = "appId",required = true) Long appId,
            @RequestParam(value = "file" ,required = false) MultipartFile file,
            @RequestPart(value = "app",required = false) String appString,
            @RequestParam(value = "avatar",required = false) MultipartFile avatar,
            @RequestParam(value = "detailImages",required = false) MultipartFile[] detailImages,
            @RequestParam(value = "moduleJson",required = false) MultipartFile moduleJson) throws IOException {




        log.info("正在进入更新方法...");


        App oldApp = appService.getAppById(appId);
        if(ObjectUtils.isEmpty(oldApp)) {
            return AjaxResult.error("更新的app为空");
        }

        //解析moduleJson
        // 读取 model.json 的内容
        if(!ObjectUtils.isEmpty(moduleJson)){
            String modelJsonContent = new String(moduleJson.getBytes(), StandardCharsets.UTF_8);
            log.error("modelJsonContent is " + modelJsonContent);
            AppModuleJson appModuleJson = AppJsonExtract(modelJsonContent);
            oldApp.setBundleName(appModuleJson.getBundleName());
            oldApp.setVersion(appModuleJson.getVersionName());
        }


        //App的JSON解析
        if(!ObjectUtils.isEmpty(appString)) {
            ObjectMapper objectMapper = new ObjectMapper();
            App app;
            try {
                app = objectMapper.readValue(appString,App.class);
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error("JSON解析失败" + e.getMessage());
            }

            log.info("当前用户id为：" + SecurityUtils.getUserId());
            app.setDeveloperId(SecurityUtils.getUserId());
            if(!ObjectUtils.isEmpty(app.getName())){oldApp.setName(app.getName());}
            if(!ObjectUtils.isEmpty(app.getDescription())){oldApp.setDescription(app.getDescription());}
            if(!ObjectUtils.isEmpty(app.getCategoryId())){oldApp.setCategoryId(app.getCategoryId());}
            if(!ObjectUtils.isEmpty(app.getVersion())){oldApp.setVersion(app.getVersion());}
            if(!ObjectUtils.isEmpty(app.getSize())){oldApp.setSize(app.getSize());}
            //判断文件的bundleName是否重复
            //String bundleName = app.getBundleName();
            //App getByBundleName= appService.getAppByBundleName(bundleName);
            //if(!ObjectUtils.isEmpty(getByBundleName)) return AjaxResult.error("文件上传失败，bundleName重复");
        }


        try {
            AliOSSUtils aliOSSUtils = new AliOSSUtils();
            //app上传
            if(!ObjectUtils.isEmpty(file)){
                String fileUrl = aliOSSUtils.upload(file, FileType.software.getCode());
                String[] split = fileUrl.split("/");
                oldApp.setDownloadUrl(split[split.length - 1].trim());
            }
            //app avatar上传
            if(!ObjectUtils.isEmpty(avatar)){
                String avatarUrl = aliOSSUtils.upload(avatar, FileType.avatar.getCode());
                oldApp.setIconUrl(avatarUrl);
            }
            //插入app的详细数据
            int update = appService.updateById(oldApp);
            if(update <=0 ) return AjaxResult.error();

            //app detail_images上传
            if(!ObjectUtils.isEmpty(detailImages)){
                appImageService.deleteByAppId(appId);
                for (MultipartFile detailImage : detailImages) {
                    String imageUrl = aliOSSUtils.upload(detailImage, FileType.images.getCode());
                    appImageService.addImage(appId,imageUrl);
                }
            }

            return AjaxResult.success("文件更新成功");

        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.error("文件更新失败" + e.getMessage());
        }
    }








    /**
     * 上传文件功能
     * @param
     * @return
     *//*
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/upload")
    public AjaxResult upload(
            @RequestParam("file") MultipartFile file,
            @RequestPart("app") String appString,
            @RequestParam("avatar") MultipartFile avatar,
            @RequestParam("detailImages") MultipartFile[] detailImages,
            @RequestParam("moduleJson") MultipartFile moduleJson) throws IOException {

        log.error("正在进入上传方法...");
        log.info("正在进入上传方法...");
        if(ObjectUtils.isEmpty(file)) return AjaxResult.error("上传文件为空");
        if(ObjectUtils.isEmpty(appString)) return AjaxResult.error("上传参数为空");

        //解析moduleJson
        // 读取 model.json 的内容
        String modelJsonContent = new String(moduleJson.getBytes(), StandardCharsets.UTF_8);
//        String modelJsonContent = new String(moduleJson.getBytes(), StandardCharsets.UTF_8);
        log.error("modelJsonContent is " + modelJsonContent);
        AppModuleJson appModuleJson = AppJsonExtract(modelJsonContent);

        //App的JSON解析
        ObjectMapper objectMapper = new ObjectMapper();
        App app;
        try {
            app = objectMapper.readValue(appString,App.class);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("JSON解析失败" + e.getMessage());
        }
        app.setBundleName(appModuleJson.getBundleName());
        app.setVersion(appModuleJson.getVersionName());
        log.info("当前用户id为：" + SecurityUtils.getUserId());
        app.setDeveloperId(SecurityUtils.getUserId());
        //判断文件的bundleName是否重复
        String bundleName = app.getBundleName();
        App getByBundleName= appService.getAppByBundleName(bundleName);
        if(!ObjectUtils.isEmpty(getByBundleName)) return AjaxResult.error("文件上传失败，bundleName重复");
        //构建软件的上传地址
        String originalFilename = file.getOriginalFilename();
        File dest = new File(BASE_UPLOAD_PATH + originalFilename);

        //构建app头像上传地址
        String avatarOriginalFilename = avatar.getOriginalFilename();
        File avatarDest = new File(BASE_AVATAR_UPLOAD_PATH + avatarOriginalFilename);

        //插入app的详细数据
        app.setIconUrl("http://192.168.0.132:8080/avatar/" + avatarOriginalFilename);
        app.setDownloadUrl(avatarOriginalFilename);
        int insert = appService.addApp(app);
        if(insert <=0 ) return AjaxResult.error();

        //插入app_images的数据
        Long id = app.getId();
        for (MultipartFile detailImage : detailImages) {
            appImageService.addImage(id,detailImage.getOriginalFilename());
        }
        try {
            //app上传
            file.transferTo(dest);
            //app avatar上传
            avatar.transferTo(avatarDest);
            //app detail_images上传
            for (MultipartFile detailImage : detailImages) {
                File imageDest = new File(BASE_DETAILS_IMAGES_UPLOAD_PATH + detailImage.getOriginalFilename());
                detailImage.transferTo(imageDest);
            }
            return AjaxResult.success("文件上传成功",originalFilename);

        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.error("文件上传失败" + e.getMessage());
        }



    }*/

    private AppModuleJson AppJsonExtract(String appModuleJson){
        AppModuleJson appModuleJsonObj = new AppModuleJson();
        try {
            // 使用 Jackson 解析 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(appModuleJson);

            // 提取 bundleName 和 versionName
            String bundleName = rootNode.path("app").path("bundleName").asText();
            String versionName = rootNode.path("app").path("versionName").asText();

            appModuleJsonObj.setBundleName(bundleName);
            appModuleJsonObj.setVersionName(versionName);
            // 打印结果
            System.out.println("Bundle Name: " + bundleName);
            System.out.println("Version Name: " + versionName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return appModuleJsonObj;
    }



}
